import Vue from 'vue'
import VueRouter from 'vue-router'
import store from "@/store"
import Welcome from '@/views/Welcome.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/Login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/Home.vue'),
    redirect: '/Welcome',
    children: [
      {
        path: '/welcome',
        name: 'welcome',
        component: Welcome
      },
      {
        path: '/users',
        name: 'users',
        component: () => import('../views/user/users.vue')
      },
      {
        path: '/rights',
        name: 'rights',
        component: () => import('../views/right/rights.vue')
      },
      {
        path: '/roles',
        name: 'role',
        component: () => import('../views/right/role.vue')
      },
      {
        path: '/goods',
        name: 'goods',
        component: () => import('../views/good/goods.vue')
      },
      {
        path: '/categories',
        name: 'categories',
        component: () => import('../views/good/categories.vue')
      },
      {
        path: '/params',
        name: 'params',
        component: () => import('../views/good/params.vue')
      },
      {
        path: '/goods/add',
        name: 'add',
        component: () => import('../views/good/add.vue')
      },
      {
        path: 'reports',
        name: 'reports',
        component: () => import('../views/reports.vue')
      }
    ]
  },
  {
    path: '/Dialog',
    name: 'Dialog',
    component: () => import('../views/Dialog.vue')
  }
]

const router = new VueRouter({
  // mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  const token = store.getters.token;
  const isLogin = to.name === 'Login'
  //如果有token，并且在登录页，那么跳转到首页
  if (token && isLogin) {
    return next({ name: 'Home' });
  }
  //如果没有token，并且不是在登录页，那么跳转到登录页
  if (!token && !isLogin) {
    return next({ name: 'Login' });
  }
  next()
})

export default router
